﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using OpenComposite.EII.RepositoryUIs;
using OpenComposite.EII.Repository;
using System.Diagnostics;

namespace OpenComposite.EII.Forms
{
	public partial class FormPDFViewer : DockContent
	{
		public FormPDFViewer(IServiceProvider serviceProvider)
		{
				InitializeComponent();
			//this.axAcroPDF1.setShowToolbar(false);
			_serviceProvider = serviceProvider;
		}

		IServiceProvider _serviceProvider;
		UCDocumentation _ucDocumentation;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			try {
				_ucDocumentation.Dispose();
				_ucDocumentation = null;
				//this.axAcroPDF1.Dispose();
				//this.axAcroPDF1 = null;
			} catch { }

			if ( disposing && ( components != null ) ) {
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		public Documentation Documentation
		{
			get;
			set;
		}

		private void FormPDFViewer_Shown(object sender, EventArgs e)
		{
			this.DockStateChanged += new EventHandler(FormPDFViewer_DockStateChanged);
			Initialize();
		}

		void FormPDFViewer_DockStateChanged(object sender, EventArgs e)
		{
			if ( Documentation != null && Documentation.BinaryDocument != null ) {
				Initialize();
			}
		}

		public void Initialize()
		{
			try {
				if ( _ucDocumentation == null ) {
					_ucDocumentation = new UCDocumentation(_serviceProvider);
					_ucDocumentation.HideHeader();
					_ucDocumentation.Dock = DockStyle.Fill;
				}
				_ucDocumentation.RepositoryItem = this.Documentation;
				if ( !this.Controls.Contains(_ucDocumentation) ) {
					this.Controls.Add(_ucDocumentation);
				}
			} catch ( System.Runtime.InteropServices.COMException comex ) {
				Trace.WriteLine(comex.Message);
				MessageBox.Show("Could not show the documentation. Please install Adobe Reader.",
								"Show Documentation", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void FormPDFViewer_FormClosing(object sender, FormClosingEventArgs e)
		{
			RepositoryService rs = _serviceProvider.GetService(typeof(RepositoryService)) as RepositoryService;
			if ( rs != null ) {
				rs.RemoveFromCache(this.Documentation);
				this.Documentation.Dispose();
			}
			Documentation = null;
		}
	}
}

